/**
 * Copyright 2018-2019 jianggujin (www.jianggujin.com).
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.jianggujin.modulelink.action.http;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Properties;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.jianggujin.modulelink.util.JAssert;
import com.jianggujin.modulelink.util.JLogFactory;
import com.jianggujin.modulelink.util.JLogFactory.JLog;

/**
 * HTTP请求处理
 * 
 * @author jianggujin
 *
 */
public abstract class JResourceHttpAction extends JGenericHttpAction {
    private static final JLog logger = JLogFactory.getLog(JResourceHttpAction.class);
    private final String[] prefixs;
    protected static final Properties MIME_TYPES = new Properties();
    private final ClassLoader classLoader;
    static {
        InputStream in = null;
        try {
            in = JResourceHttpAction.class.getResourceAsStream("mime-type.properties");
            MIME_TYPES.load(in);
        } catch (Exception e) {
            logger.error("load mime type error", e);
        }
    }

    public JResourceHttpAction(String[] prefixs) {
        JAssert.checkNotNull(prefixs, "prefixs must not be null");
        this.classLoader = getClass().getClassLoader();
        this.prefixs = prefixs;
    }

    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response)
            throws IOException, ServletException {
        String url = request.getRequestURI();
        String contextPath = request.getContextPath();
        if (!"/".equals(contextPath)) {
            url = url.substring(contextPath.length());
        }
        int index = url.lastIndexOf('.');
        if (index > -1) {
            String mimeType = MIME_TYPES.getProperty(url.substring(index + 1));
            if (mimeType != null) {
                response.setContentType(mimeType);
            }
        }
        InputStream in = null;
        if (this.prefixs.length == 0) {
            in = this.classLoader.getResourceAsStream(this.trim(url));
        } else {
            for (String prefix : this.prefixs) {
                String name = prefix + url;
                in = this.classLoader.getResourceAsStream(this.trim(name));
                if (in != null) {
                    break;
                }
            }
        }
        if (in != null) {
            OutputStream out = response.getOutputStream();
            byte[] buffer = new byte[512];
            int len = -1;
            while ((len = in.read(buffer)) != -1) {
                out.write(buffer, 0, len);
            }
            out.flush();
            in.close();
            out.close();
        } else {
            response.sendError(404);
        }
    }

    private String trim(String url) {
        while ('/' == url.charAt('/')) {
            url = url.substring(1);
        }
        return url;
    }
}
